package thread;

class MyBlockingQueue {
    private String[] data = null;

    private int head = 0;//队首

    private int tail = 0;//队尾

    private int size = 0;//元素个数

    public MyBlockingQueue(int capacity) {
        data  = new String[capacity];

    }

    public void put(String elem) throws InterruptedException {
        synchronized (this) {
            while(size >= data.length) {
                //队列已满。需要阻塞
                //return;
                this.wait();
            }
            data[head] = elem;
            tail++;
            if (tail >= data.length) {
                tail = 0;
            }
            //同上
            //tail = (tail + 1) % data.length;

            size++;
            this.notify();
        }
    }

    public String take() throws InterruptedException {
        synchronized (this) {
            while(size == 0) {
                //队列为空。需要阻塞
                //return null;
                this.wait();
            }
            String ret = data[head];
            head++;
            if (head >= data.length) {
                head = 0;

            }
            size--;
            this.notify();
            return ret;
        }
    }
}

public class Demo31 {
    public static void main(String[] args) {
        MyBlockingQueue myBlockingQueue = new MyBlockingQueue(1000);

        Thread t1 = new Thread(() ->{

            int n = 0;
            while(true) {
                try{
                    myBlockingQueue.put(n+"");
                    System.out.println("生产元素： "+n);
                    n++;
                }catch (InterruptedException e){
                    throw new RuntimeException(e);
                }
            }
        });

        Thread t2 = new Thread(() ->{
            while(true) {
                String n  =null;
                try{
                    n = myBlockingQueue.take();
                    System.out.println("消费元素："+n);
                    Thread.sleep(1000);
                }catch (InterruptedException e){
                    throw new RuntimeException(e);
                }
            }
        });

        t1.start();
        t2.start();
    }
}
